﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace ShowWindowIntelligence
{
    public partial class LazyInitializer : Component
    {
        private readonly List<Control> controls = new List<Control>();

        public event EventHandler InitializeControl;

        public LazyInitializer()
        {
            InitializeComponent();
        }

        public LazyInitializer(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        [Category("Behaviors"), Browsable(false)]
        public IList<Control> Controls
        {
            get { return controls; }
        }

        public void Start()
        {
            SetControlAvailability(false);
            StartInitialize();
        }

        private void StartInitialize()
        {
            if (null == InitializeControl) return;
            InitializeControl.BeginInvoke(this, EventArgs.Empty, EndInitialize, null);
        }

        private void EndInitialize(IAsyncResult result)
        {
            try
            {
                SetControlAvailability(true);
                InitializeControl.EndInvoke(result);
            }
            catch {  } // ignore all errors here
        }

        private void SetControlAvailability(bool value)
        {
            foreach (Control control in Controls)
            {
                EventHandler handler = delegate { control.Enabled = value; };
                if (control.InvokeRequired)
                {
                    control.Invoke(handler, this, EventArgs.Empty);
                }
                else
                {
                    control.Enabled = value;
                }
            }
        }
    }
}